package com.sdhs.myproject.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.sdhs.myproject.domain.GcMyprojectInformation;
import com.sdhs.system.domain.GcContract;
import com.sdhs.system.mapper.GcContractMapper;
import com.sdhs.util.BidUtilization;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sdhs.myproject.mapper.GcMyprojectContractInformationMapper;
import com.sdhs.myproject.domain.GcMyprojectContractInformation;
import com.sdhs.myproject.service.IGcMyprojectContractInformationService;

/**
 * 我的项目--项目合同信息Service业务层处理
 *
 * @author andong
 * @date 2025-03-11
 */
@Service
public class GcMyprojectContractInformationServiceImpl implements IGcMyprojectContractInformationService
{
    @Autowired
    private GcMyprojectContractInformationMapper gcMyprojectContractInformationMapper;

    @Autowired
    private GcContractMapper gcContractMapper;
    /**
     * 查询我的项目--项目合同信息
     *
     * @param id 我的项目--项目合同信息主键
     * @return 我的项目--项目合同信息
     */
    @Override
    public GcMyprojectContractInformation selectGcMyprojectContractInformationById(Long id)
    {
        return gcMyprojectContractInformationMapper.selectGcMyprojectContractInformationById(id);
    }

    /**
     * 查询我的项目--项目合同信息列表
     *
     * @param gcMyprojectContractInformation 我的项目--项目合同信息
     * @return 我的项目--项目合同信息
     */
    @Override
    public List<GcMyprojectContractInformation> selectGcMyprojectContractInformationList(GcMyprojectContractInformation gcMyprojectContractInformation)
    {
        return gcMyprojectContractInformationMapper.selectGcMyprojectContractInformationList(gcMyprojectContractInformation);
    }

    /**
     * 新增我的项目--项目合同信息
     *
     * @param gcMyprojectContractInformation 我的项目--项目合同信息
     * @return 结果
     */
    @Override
    public int insertGcMyprojectContractInformation(GcMyprojectContractInformation gcMyprojectContractInformation)
    {
        return gcMyprojectContractInformationMapper.insertGcMyprojectContractInformation(gcMyprojectContractInformation);
    }

    /**
     * 修改我的项目--项目合同信息
     *
     * @param gcMyprojectContractInformation 我的项目--项目合同信息
     * @return 结果
     */
    @Override
    public int updateGcMyprojectContractInformation(GcMyprojectContractInformation gcMyprojectContractInformation)
    {
        return gcMyprojectContractInformationMapper.updateGcMyprojectContractInformation(gcMyprojectContractInformation);
    }
    /**
     * 修改我的项目--项目合同信息
     *
     * @param gcMyprojectContractInformation 我的项目--根据项目id和合同id修改
     * @return 结果
     */
    @Override
    public int updateGcMyProjectContractInformationByProject(GcMyprojectContractInformation gcMyprojectContractInformation)
    {
        return gcMyprojectContractInformationMapper.updateGcMyProjectContractInformationByProject(gcMyprojectContractInformation);
    }

    /**
     * 批量删除我的项目--项目合同信息
     *
     * @param ids 需要删除的我的项目--项目合同信息主键
     * @return 结果
     */
    @Override
    public int deleteGcMyprojectContractInformationByIds(Long[] ids)
    {
        return gcMyprojectContractInformationMapper.deleteGcMyprojectContractInformationByIds(ids);
    }

    /**
     * 项目看板合同数据
     */
    @Override
    public GcMyprojectContractInformation  getAll(Long[] ids)
    {
         List<GcMyprojectContractInformation> gcMyprojectContractInformation = gcMyprojectContractInformationMapper.getAll(ids);
         GcMyprojectContractInformation moneyAll = gcMyprojectContractInformationMapper.getMoneyAll(ids);
         GcMyprojectContractInformation fillMoney = gcMyprojectContractInformationMapper.getFillMoney(ids);
         GcMyprojectContractInformation payMoney = gcMyprojectContractInformationMapper.getPayMoney(ids);
        // 初始化总金额
        BigDecimal totalFillMoney = BigDecimal.ZERO; // 收入类合同总金额
        BigDecimal totalPayMoney = BigDecimal.ZERO; // 支出类合同总金额
        // 过滤掉num为空的记录
        List<GcMyprojectContractInformation> filteredGcMyprojectContractInformation = new ArrayList<>();
        for (GcMyprojectContractInformation con : gcMyprojectContractInformation){
            if (con != null && con.getNum() != null){
                filteredGcMyprojectContractInformation.add(con);
            }
        }
        if (!filteredGcMyprojectContractInformation.isEmpty()) {
            // 2. 收集所有主合同的编号（用于批量查询子合同）
            List<String> mainContractNums = filteredGcMyprojectContractInformation.stream()
                    .map(GcMyprojectContractInformation::getNum)
                    .toList();
            // 3. 批量查询所有子合同（IsSupplementaryContract = "1" 且 OriginalContractNum 在 mainContractNums 中）
            GcContract queryParam = new GcContract();
            queryParam.setIsSupplementaryContract("1");
            queryParam.setOriginalContractNums(mainContractNums); // 假设 Mapper 支持批量查询
            List<GcContract> supplementaryContracts = gcContractMapper.selectGcContractList(queryParam);
            // 将合同数据转为我的合同数据
            List<GcMyprojectContractInformation> supplementaryInfoList = supplementaryContracts.stream()
                    .map(suppContract -> {
                        GcMyprojectContractInformation info = new GcMyprojectContractInformation();
                        BeanUtils.copyProperties(suppContract, info);
                        return info;
                    })
                    .toList();

            // 按 OriginalContractNum 分组（Key=主合同Num，Value=对应的子合同列表）
            Map<String, List<GcMyprojectContractInformation>> supplementaryMap = supplementaryInfoList.stream()
                    .collect(Collectors.groupingBy(GcMyprojectContractInformation::getOriginalContractNum));

            // 遍历主合同，设置 money 和子合同
            for (GcMyprojectContractInformation mainContract : filteredGcMyprojectContractInformation) {

                // 获取子合同列表
                List<GcMyprojectContractInformation> children = supplementaryMap.getOrDefault(mainContract.getNum(), Collections.emptyList());
                mainContract.setChildren(children);
                // 遍历子合同，如果 contractMoney 有值，且子合同不为空 则赋值给子合同 money
                if (mainContract.getContractMoney() != null && children.size()>0) {
                    for (GcMyprojectContractInformation child : children) {
                        if (mainContract.getContractMoney() != null) {
                            child.setMoney(mainContract.getContractMoney());
                        }
                    }
                    // 如果 contractMoney 有值，且子合同为空 则赋值给主合同 money
                }else if (mainContract.getContractMoney() != null && children.size()==0){
                    mainContract.setMoney(mainContract.getContractMoney());
                }
            }
            // 遍历合同，赋值支出类合同总额，收入类合同总额，

            for (GcMyprojectContractInformation mainContract : filteredGcMyprojectContractInformation) {

                if(mainContract.getIncomeExpenseType().equals("收入类")&& !mainContract.getChildren().isEmpty()){
                    if(mainContract.getChildren().get(0).getMoney() != null){
                        totalFillMoney = totalFillMoney.add(mainContract.getChildren().get(0).getMoney());
                    }
                }else if(mainContract.getIncomeExpenseType().equals("收入类")&& mainContract.getChildren().isEmpty()){
                    if(mainContract.getMoney() != null){
                        totalFillMoney = totalFillMoney.add(mainContract.getMoney());
                    }
                }
                else if (mainContract.getIncomeExpenseType().equals("支出类")&& !mainContract.getChildren().isEmpty()){
                    if(mainContract.getChildren().get(0).getMoney() != null){
                        totalPayMoney =totalPayMoney.add(mainContract.getChildren().get(0).getMoney());
                    }
                }
                else if (mainContract.getIncomeExpenseType().equals("支出类")&& mainContract.getChildren().isEmpty()){
                    if(mainContract.getMoney() != null){
                        totalPayMoney =totalPayMoney.add(mainContract.getMoney());
                    }
                }
            }

        }
         GcMyprojectContractInformation contractInformation = new GcMyprojectContractInformation();
        contractInformation.setTotalFillMoney(totalFillMoney != null ? totalFillMoney : BigDecimal.ZERO);
        contractInformation.setTotalPayMoney(totalPayMoney != null ? totalPayMoney : BigDecimal.ZERO);
        contractInformation.setPayMoney(payMoney != null && payMoney.getPayMoney() != null
                ? payMoney.getPayMoney()
                : BigDecimal.ZERO);
        contractInformation.setFillMoney(fillMoney != null && fillMoney.getFillMoney() != null
                ? fillMoney.getFillMoney()
                : BigDecimal.ZERO);
        contractInformation.setManagementMoney(moneyAll != null && moneyAll.getManagementMoney() != null
                ? moneyAll.getManagementMoney()
                : BigDecimal.ZERO);
        return contractInformation;
    }
    /**
     * 删除我的项目--项目合同信息信息
     *
     * @param id 我的项目--项目合同信息主键
     * @return 结果
     */
    @Override
    public int deleteGcMyprojectContractInformationById(Long id, List<String> contractInfoIdList)
    {
         int i = gcMyprojectContractInformationMapper.deleteGcMyprojectContractInformationById(id, contractInfoIdList);
        /*删除合同支付的时候计算我的项目-利润率测试-实施期利润率*/
        BidUtilization.UpdateBidUtilization(id);
        return i;
    }
}
